import React, { useState, useEffect } from "react";
import { View, StyleSheet, Dimensions } from "react-native";
import { Input } from "@rneui/themed";
import { useSelector, useDispatch } from "react-redux";
import IconNavBar from '@/components/IconNavBar'
import { sectokenAccountSettingEditProps } from '@/config/navigatorProps'
import { getValue, setObjectValue } from '@/utils/deviceStorage'

const { width, scale } = Dimensions.get('window')
const ratio = width * scale / 1080

const SectokenAccountSettingEdit = (props) => {

    const dispatch = useDispatch()
    const [safeName, setSafeName] = useState()
    const selectedSafeWallet = useSelector((state) => state.sectokenMainReducer.selectedSafeWallet || {});

    useEffect(() => {
        if (selectedSafeWallet) {
            setSafeName(selectedSafeWallet.label || '')
        }
    }, [selectedSafeWallet]);

    const handlePressLeft = () => {
        props.navigation.goBack()
    }

    const handlePressRightTitle = () => {
        if (safeName && safeName.length > 0) {
            let obj = {
                ...selectedSafeWallet,
                label: safeName
            }
            dispatch({ type: "setSelectedSafeWallet", value: obj });
            let result = getValue('safeWalletList')
            if (result && result.length > 0) {
                result.map((item) => {
                    if (item.id === obj.id) {
                        item.label = safeName
                    }
                })
            }
            setObjectValue('safeWalletList', [...result])
            props.navigation.goBack()
        }
    }

    return (
        <View style={styles.container}>
            <IconNavBar {...props} {...sectokenAccountSettingEditProps} handlePressLeft={handlePressLeft} handlePressRightTitle={handlePressRightTitle} />
            <View style={{ alignItems: 'center' }}>
                <Input
                    containerStyle={{ ...styles.text_input, paddingLeft: 15 * ratio, marginTop: 15 * ratio }}
                    onChangeText={text => setSafeName(text)}
                    value={safeName}
                    placeholderTextColor='#767B7D'
                    inputContainerStyle={{ borderBottomWidth: 0 }}
                    inputStyle={{ fontSize: 14 }}
                />
            </View>
        </View>
    )
}

const styles = StyleSheet.create({
    container: {
        flex: 1,
        backgroundColor: '#FFFFFF'
    },
    text_input: {
        width: 330 * ratio,
        height: 44 * ratio,
        backgroundColor: '#FFFFFF',
        borderWidth: 1,
        borderColor: '#D1D1D1'
    }
})
export default SectokenAccountSettingEdit